<?php

class McCube_Template extends McCube_Template_Buffer{

    public    static $debug     = false;
    public    static $loops     = array();
    public    static $blocks    = array();
    public    static $variables = array();

    protected static $_config   = array();
    public    static $helpers   = array(
          'Html'  => 'McCube_Template_Helper_Html'
         ,'Html+' => 'McCube_Template_Helper_Html_Level2'
    );

    /** */
    public static function init(array $config=array()){
        self::$_config = $config;
        if(!isset($config['extension']))
            self::$_config['extension'] = '.tpl';

        if(isset($config['debug']) && self::$_config['debug'])
            self::$debug = isset($config['debug_strict'])
                && $config['debug_strict']
                    ? 'strict'
                    : true
            ;
    }

    public $bundle = null;

    public function __construct($bundle){
        $this->bundle = $bundle;
    }

    public function addLoop($name, array $values){
        self::$loops[$name] = $values;
        return $this;
    }

    public function addBlock($name, $value){
        self::$blocks[$name] = $value;
        return $this;
    }

    public function addVar($name, $value){
        self::$variables[$name] = $value;
        return $this;
    }

    /** */
    public function fetch($filename, $varsForBuffer=array()){
        self::$variables = array_merge(self::$variables, $varsForBuffer);

        $varsForBuffer = self::$variables;
        if(self::$_config['cache']){
            $fileCache = $this->getPathname($filename, false, true);
            $this->_cacheOnFile($fileCache, $this->parse($filename, true));
            return parent::bufferFile($fileCache, $varsForBuffer);
        } else {
            return parent::bufferString($this->parse($filename), $varsForBuffer);
        } if($cache)
            $this->_cacheOnFile($file);
    }

    /** */
    public function parse($file, $cache=false){
        $content = file_get_contents($this->getPathname($file));
        $content = $this->parseString($content);
        return $content;
    }

    /** */
    public function parseString($string, $phpTag=true){
        $string = $this->parseStringBlock ($string);
        $string = $this->parseStringInline($string);
        return str_replace('\{','{',$string);
    }

    public function parseStringInline($string, $globalDelimiters=true, $phpTags=true){
        $model = new McCube_Template_Parser_Inline($this);
        return $model->parse($string, $globalDelimiters, $phpTags);
    }

    public function parseStringBlock($string, $globalDelimiters=true, $phpTags=true){
        $model = new McCube_Template_Parser_Block($this);
        return $model->parse($string, $globalDelimiters, $phpTags);
    }

    /** */
	public function getPathname($filename, $checkExistFile=true, $cache=false){
	    if($cache)
	        $filename = McCube_Bundle::getBundle('/application')->subPaths['cache']
	            .$this->bundle->name.DIRECTORY_SEPARATOR.$filename.'.cache.php'
	       ;
	    else
	        $filename = $this->bundle->subPaths['views'].$filename.self::$_config['extension'];

        if($checkExistFile && !(is_file($filename)) && self::$debug)
			throw new McCube_Exception_FileNotFound($filename);

        return $filename;
	}

    /** */
    protected function _cacheOnFile($file, $content){
        $basedir = dirname($file);
        if(!is_dir($basedir))
            mkdir($basedir,'0777', true);

        file_put_contents($file, trim($content));
    }

    /** */
    protected function _block($name, $defaultValue){
        if(!isset(self::$blocks[$name])){
            if(self::$debug && !$defaultValue){
                if('strict' === self::$debug)
                    throw new McCube_Exception_VariableNotFound('Block [ '.$name.' ]');

                return '!-[ #BLOCK '.$name.' ]-!';
            }
            return $defaultValue;
        }
        return self::$blocks[$name];
    }
}